package controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

public class Search {

	public int generateFrequency(String query) {
		
		query = query.replaceAll(" ", "+");
		URL url;

		try {
			url = new URL(
					"http://api.bing.net/json.aspx?Appid=83770C31BCD819CBF90EB3F6A955B02717BBA2EA&query=\""
							+ query + "\"&sources=web");
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					url.openStream()));
			JSONObject jsonObj;
			jsonObj = new JSONObject(reader.readLine());
			reader.close();
			return (Integer.parseInt(jsonObj.getJSONObject("SearchResponse")
					.getJSONObject("Web").get("Total").toString()));
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return -1;
		} catch (JSONException e) {
			e.printStackTrace();
			return -1;
		} catch (IOException e) {
			e.printStackTrace();
			return -1;
		}
	}

	public int generateFrequency(String source, String target) {

		source = source.replaceAll(" ", "+");
		target = target.replaceAll(" ", "+");
		
		URL url;
		
		try {
			url = new URL(
					"http://api.bing.net/json.aspx?Appid=83770C31BCD819CBF90EB3F6A955B02717BBA2EA&query=\""
							+ source
							+ "\"+and+\""
							+ target
							+ "\"&sources=web&Web.Count=1");
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					url.openStream()));
			JSONObject jsonObj;
			System.out.println(url);
			jsonObj = new JSONObject(reader.readLine());
			reader.close();
			return (Integer.parseInt(jsonObj.getJSONObject("SearchResponse")
					.getJSONObject("Web").get("Total").toString()));
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		}
	}

	/*
	 * Pattern padrao = Pattern.compile(
	 * "de [0-9]*[.]?[0-9]*[.]?[0-9]*[.]?[0-9]* resultados</span>"); Matcher
	 * pesquisa = padrao.matcher(linha); pesquisa.find(); String y =
	 * pesquisa.group(); System.out.println(y.replaceAll("\\D", ""));
	 * 
	 * url.openConnection(); InputStream is = url.openStream();
	 * InputStreamReader isr = new InputStreamReader(is); BufferedReader br =
	 * new BufferedReader(isr); StringBuilder html = new StringBuilder(); String
	 * x = ""; while (null != ((x = br.readLine()))) { html.append(x); }
	 * System.out.println(html.toString().split(
	 * "<span class=\"sb_count\" id=\"count\">"
	 * )[1].split("de ")[1].split(" resultados")[0]);
	 * 
	 * URL url = new URL(
	 * "https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=Paris%20Hilton"
	 * ); BufferedReader reader = new BufferedReader(new
	 * InputStreamReader(url.openStream())); JSONObject jsonObj = new
	 * JSONObject(reader.readLine()); reader.close();
	 */

	// http://api.bing.net/json.aspx?Appid=83770C31BCD819CBF90EB3F6A955B02717BBA2EA&query=sushi&sources=web&Web.Count=1

}
